package com.py.credit.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.ServiceException;
import com.py.credit.dao.BatchFileDao;
import com.py.credit.dao.BatchLogDao;
import com.py.credit.dao.ColumnDao;
import com.py.credit.entity.BatchLog;
import com.py.credit.entity.Column;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.Table;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.common.LogEnum;
import com.py.credit.service.ContentService;
import com.py.credit.service.DataEntryService;
import com.py.credit.service.StepLogService;
import com.py.credit.service.TableService;
import com.py.credit.service.WriteLogsService;
import com.py.credit.service.XydDataCollectionService;
import com.py.credit.service.excel.read.service.InspectDataStyleService;
import com.py.credit.utils.UuidUtil;

@Service
public class XydDataCollectionServiceImpl implements XydDataCollectionService {
	
    private static final String CHECKREPEAT_NO = "N";
    	@Autowired
	   private BatchLogDao batchLogDao;

	    @Autowired
	    private ContentService contentService;

	    @Autowired
	    private BatchFileDao batchFileDao;

	    @Autowired
	    private ColumnDao columnDao;

	    @Autowired
	    private WriteLogsService writeLogsService;

	    @Autowired
	    private TableService tableService;

	    @Autowired
	    @Qualifier("default")
	    private InspectDataStyleService inspectDataStyleService;

	    @Autowired
	    private DataEntryService dataEntryService;

	    @Autowired
	    private StepLogService stepLogService;

	 @Override
	 @Transactional
	public void manualCollection(String data, Integer tableId, SysUser userInfo, Integer contentId) {
		 StringBuilder error = new StringBuilder();
	        // 获取数据表信息
	        Table table = tableService.queryCubeById(tableId);
	        table.setRootId(100000);
	        // 获取数据表列信息
	        // List<Column> columns = columnService.getListByTableId(tableId);
	        Long topDeptId = userInfo.getOfficeId();
	        String pIds = userInfo.getAllParentId();
	        if (StringUtils.isNotBlank(pIds)) {
	            String t = StringUtils.split(pIds, ",")[0];
	            topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
	        }

	        String tipId = tableId + "_" + topDeptId;
	        TableResult table1 = contentService.getTableColumns(tableId, contentId, tipId);
	        List<Column> columns = table1.getColumns();
	        String batchId = UuidUtil.getInstance().getUUid();
	        // 新增批次信息
	        batchLogDao.addBatchLog(batchId.toString(), tableId, "2", 100000, userInfo.getOfficeId(), userInfo.getId(),
	                LogEnum.CLZ, null);
	        // 获取批次详细信息
	        BatchLog batchLog = batchLogDao.select(batchId);
	        List<Map<String, Object>> listDataMap = JSONObject.parseObject(data.replaceAll(" ", ""),
	                new TypeReference<List<Map<String, Object>>>() {
	                });
	   
	        int size = listDataMap.size();
	        // 处理流程日志
	        stepLogService.addStepLog(batchId, "解析数据上报到的" + size + "条数据。");
	        // 重复性校验
	        stepLogService.addStepLog(batchId, "开始重复性校验：0到" + size + "行数据。");

	        // 数据是否需要重复性校验
	        boolean checkRepeat = true;
	        if (CHECKREPEAT_NO.equals(table.getRepeatCheck())) {
	            checkRepeat = false;
	        }
	        // 数据重复性校验
	        Map<String, Object> duplicationCheck = inspectDataStyleService.duplicationCheck(listDataMap, table, columns,
	                false, checkRepeat);
	        String duplicationMess = String.valueOf(duplicationCheck.get("duplicationMess"));
	        if (null != duplicationCheck && StringUtils.isNotEmpty(duplicationMess)) {
	            error.append(duplicationMess);
	            // 通过抛出异常执行回滚
	            throw new ServiceException(error.toString());
	        }
	        stepLogService.addStepLog(batchId, "开始将手工采集的0到" + size + "行数据录入至清洗库。");
	        dataEntryService.addSuccessData(listDataMap, table, batchLog, columns);
	        stepLogService.addStepLog(batchId, "结束将手工采集的0到" + size + "行数据录入至清洗库。");	    
	            // 未异常更新本次数据数量
	        int duplicationCount = Integer.parseInt(null != duplicationCheck.get("duplicationCount")
	                    ? String.valueOf(duplicationCheck.get("duplicationCount")) : "0");
	            batchLogDao.modifyBatchLog(batchId, LogEnum.EX_RESULT_S, size, size - duplicationCount,
	                    0, duplicationCount, 0, LogEnum.YWC);
	       

	}

}
